package com.damai.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.citywithincity.utils.ConfigReader;
import com.citywithincity.utils.DateTimeUtil;
import com.citywithincity.utils.IoUtil;
import com.damai.action.factories.WebActionFactory;
import com.damai.annotation.Action;
import com.damai.annotation.Controller;
import com.damai.mvc.view.imple.BytesView;
import com.damai.utils.FileUtil;
import com.damai.utils.FileVisitor;
import com.damai.utils.ZipUtils;

@Action(WebActionFactory.class)
@Controller(key = "php")
public class PhpVersionController {

	public BytesView exportVersion(String date) throws IOException, ParseException{
		ConfigReader reader = ConfigReader.getReader("other.properties");
		String dir = reader.get("php_dir");
		String dest = reader.get("php_dest");
		
		Date sortDate = DateTimeUtil.parseShortDate(date);
		final long startTime = sortDate.getTime();
		final List<File> list = new ArrayList<File>();
		FileUtil.scan(new File(dir), new FileVisitor() {
			
			@Override
			public void visitFile(File file) {
				if(file.isDirectory())return;
				String name = file.getName();
				if(name.endsWith("php") 
						|| name.endsWith("css") 
						|| name.endsWith("js")
						|| name.endsWith("png")
						|| name.endsWith("jpg")){
					if(file.lastModified() > startTime ){
						list.add(file);
					}
					
				}
			}
		});
		//拷贝进入这个文件夹
		File destDir = new File(dest,String.valueOf(System.currentTimeMillis()));
		if(!destDir.exists()){
			destDir.mkdirs();
		}
		
		StringBuilder sb = new StringBuilder();

		
		List<File> destFiles = new ArrayList<File>();
		for (File file : list) {
			String realFile = file.getAbsolutePath().substring(dir.length());
			sb.append(realFile).append("\r\n");
			File destFile = new File(destDir,realFile);
			File parentFile = destFile.getParentFile();
			if(parentFile.getName().contains("logs")){
				continue;
			}
			System.out.println(parentFile);
			if(!parentFile.exists()){
				parentFile.mkdirs();
			}
			
			FileUtil.copy(file, destFile);
			destFiles.add(destFile);
		}
		
		System.out.println(sb.toString());
		//文件列表
		File fileList = new File(destDir,"_fileList.txt");
		IoUtil.write(fileList, sb.toString().getBytes());
		
		File file = new File(destDir.getAbsolutePath()+".zip");
		ZipUtils.compress(destDir,file );
		
		return new BytesView(IoUtil.readFromFile(file),file.getName());
	}
	
	
}
